package sc.prototype.common;

import groovy.lang.GroovyClassLoader;

public class GroovyUtil {

    public static <T> T parseTextGetInstance(String text, Class<T> returnType) throws InstantiationException,
            IllegalAccessException {
        Class<T> parseClass = parseText(text, returnType);
        T ret = parseClass.newInstance();
        return ret;
    }

    @SuppressWarnings("unchecked")
    public static <T> Class<T> parseText(String text, Class<T> returnType) {
        GroovyClassLoader classLoader = new GroovyClassLoader();
        Class<?> parseClass = classLoader.parseClass(text);
        if (!returnType.isAssignableFrom(parseClass)) {
            String error = "Groovy编译结果异常，类型[" + returnType + "]不满足，实际类型[" + parseClass + "]";
            throw new IllegalArgumentException(error);
        }
        return (Class<T>) parseClass;
    }

}
